<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>斐波那契金融分析工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .description {
            color: #7f8c8d;
            font-size: 16px;
            margin-bottom: 20px;
        }

        .input-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #34495e;
        }

        input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #2980b9;
        }

        .results-section {
            margin-top: 30px;
        }

        .chart-container {
            height: 400px;
            margin-bottom: 30px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .data-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .data-table tr:hover {
            background-color: #f5f5f5;
        }

        .analysis-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .analysis-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .analysis-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .golden-ratio {
            color: #f39c12;
            font-weight: bold;
        }

        .growth-positive {
            color: #27ae60;
        }

        .growth-negative {
            color: #e74c3c;
        }

        footer {
            text-align: center;
            margin-top: 30px;
            color: #7f8c8d;
            font-size: 14px;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .chart-container {
                height: 300px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <header>
            <h1>斐波那契金融分析工具</h1>
            <p class="description">基于斐波那契数列的金融投资分析与预测工具</p>
        </header>

        <div class="input-section">
            <div class="form-group">
                <label for="periods">请输入期数 (1-50):</label>
                <input type="number" id="periods" min="1" max="50" value="10">
            </div>
            <div class="form-group">
                <label for="initialInvestment">初始投资金额 (元):</label>
                <input type="number" id="initialInvestment" min="100" value="10000">
            </div>
            <button id="calculate">计算分析</button>
        </div>

        <div class="results-section" id="results" style="display: none;">
            <h2>分析结果</h2>
            <div class="chart-container">
                <canvas id="fibonacciChart"></canvas>
            </div>

            <h3>数据明细</h3>
            <div class="table-responsive">
                <table class="data-table" id="dataTable">
                    <thead>
                        <tr>
                            <th>期数</th>
                            <th>斐波那契值</th>
                            <th>投资金额 (元)</th>
                            <th>增长率 (%)</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>

            <div class="analysis-section">
                <h3>投资分析</h3>
                <div id="analysisContent">
                    <!-- 分析内容将通过JavaScript动态填充 -->
                </div>
            </div>
        </div>

        <footer>
            <p>© 2023 斐波那契金融分析工具 | 基于斐波那契数列算法</p>
        </footer>
    </div>

    <!-- 引入Chart.js库用于图表绘制 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
        // 斐波那契数列计算函数
        const fibonacci = n =>
            Array.from({ length: n }).reduce(
                (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : (i === 0 ? 1 : i)),
                []
            );

        // 计算增长率
        const calculateGrowthRate = (current, previous) => {
            if (previous === 0 || isNaN(previous)) return 0;
            return ((current - previous) / previous * 100).toFixed(2);
        };

        // 计算黄金比例接近度
        const calculateGoldenRatioProximity = (current, previous) => {
            if (previous === 0 || isNaN(previous) || current === 0 || isNaN(current)) return 0;
            const ratio = current / previous;
            const goldenRatio = 1.618034; // 黄金比例值
            return Math.abs(ratio - goldenRatio).toFixed(4);
        };

        // 格式化数字为带千分位的格式
        const formatNumber = (num) => {
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        };

        // 初始化图表
        let fibChart;

        // 处理计算按钮点击事件
        document.getElementById('calculate').addEventListener('click', function () {
            const periods = parseInt(document.getElementById('periods').value);
            const initialInvestment = parseFloat(document.getElementById('initialInvestment').value);

            if (isNaN(periods) || periods < 1 || periods > 50) {
                alert('请输入1-50之间的有效期数');
                return;
            }

            if (isNaN(initialInvestment) || initialInvestment < 100) {
                alert('请输入至少100元的初始投资金额');
                return;
            }

            // 计算斐波那契数列
            const fibSequence = fibonacci(periods);

            // 计算投资金额
            const investmentAmounts = fibSequence.map(value => value * initialInvestment);

            // 显示结果区域
            document.getElementById('results').style.display = 'block';

            // 绘制图表
            drawChart(fibSequence, investmentAmounts);

            // 填充数据表格
            populateTable(fibSequence, investmentAmounts);

            // 生成分析报告
            generateAnalysis(fibSequence, investmentAmounts);
        });

        // 绘制图表函数
        function drawChart(fibSequence, investmentAmounts) {
            const ctx = document.getElementById('fibonacciChart').getContext('2d');

            // 如果图表已存在，销毁它
            if (fibChart) {
                fibChart.destroy();
            }

            // 创建标签数组
            const labels = fibSequence.map((_, index) => `第${index + 1}期`);

            // 创建新图表
            fibChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '斐波那契数列值',
                            data: fibSequence,
                            borderColor: 'rgba(54, 162, 235, 1)',
                            backgroundColor: 'rgba(54, 162, 235, 0.1)',
                            borderWidth: 2,
                            pointRadius: 3,
                            tension: 0.1,
                            yAxisID: 'y'
                        },
                        {
                            label: '投资金额 (元)',
                            data: investmentAmounts,
                            borderColor: 'rgba(255, 99, 132, 1)',
                            backgroundColor: 'rgba(255, 99, 132, 0.1)',
                            borderWidth: 2,
                            pointRadius: 3,
                            tension: 0.1,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: '斐波那契值'
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            title: {
                                display: true,
                                text: '投资金额 (元)'
                            },
                            grid: {
                                drawOnChartArea: false,
                            },
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.datasetIndex === 1) {
                                        label += '¥' + formatNumber(context.raw.toFixed(2));
                                    } else {
                                        label += context.raw;
                                    }
                                    return label;
                                }
                            }
                        }
                    }
                }
            });
        }

        // 填充数据表格函数
        function populateTable(fibSequence, investmentAmounts) {
            const tableBody = document.getElementById('tableBody');
            tableBody.innerHTML = '';

            fibSequence.forEach((value, index) => {
                const row = document.createElement('tr');

                // 期数
                const periodCell = document.createElement('td');
                periodCell.textContent = index + 1;
                row.appendChild(periodCell);

                // 斐波那契值
                const fibCell = document.createElement('td');
                fibCell.textContent = value;
                row.appendChild(fibCell);

                // 投资金额
                const investmentCell = document.createElement('td');
                investmentCell.textContent = '¥' + formatNumber(investmentAmounts[index].toFixed(2));
                row.appendChild(investmentCell);

                // 增长率
                const growthCell = document.createElement('td');
                const growthRate = index > 0 ? calculateGrowthRate(investmentAmounts[index], investmentAmounts[index - 1]) : '-';
                growthCell.textContent = growthRate === '-' ? growthRate : growthRate + '%';

                if (growthRate !== '-') {
                    if (parseFloat(growthRate) > 0) {
                        growthCell.classList.add('growth-positive');
                    } else if (parseFloat(growthRate) < 0) {
                        growthCell.classList.add('growth-negative');
                    }
                }

                row.appendChild(growthCell);

                tableBody.appendChild(row);
            });
        }

        // 生成分析报告函数
        function generateAnalysis(fibSequence, investmentAmounts) {
            const analysisContent = document.getElementById('analysisContent');
            analysisContent.innerHTML = '';

            // 计算总投资回报
            const initialInvestment = investmentAmounts[0];
            const finalInvestment = investmentAmounts[investmentAmounts.length - 1];
            const totalReturn = finalInvestment - initialInvestment;
            const returnRate = (totalReturn / initialInvestment * 100).toFixed(2);

            // 创建总回报分析项
            const totalReturnItem = document.createElement('div');
            totalReturnItem.classList.add('analysis-item');
            totalReturnItem.innerHTML = `
                <h4>总投资回报</h4>
                <p>初始投资: ¥${formatNumber(initialInvestment.toFixed(2))}</p>
                <p>最终价值: ¥${formatNumber(finalInvestment.toFixed(2))}</p>
                <p>总回报: <span class="${totalReturn >= 0 ? 'growth-positive' : 'growth-negative'}">¥${formatNumber(Math.abs(totalReturn).toFixed(2))} (${returnRate}%)</span></p>
            `;
            analysisContent.appendChild(totalReturnItem);

            // 黄金比例分析
            const goldenRatioItem = document.createElement('div');
            goldenRatioItem.classList.add('analysis-item');

            // 找出最接近黄金比例的两个连续数
            let closestPair = { index: 1, proximity: Infinity };
            for (let i = 2; i < fibSequence.length; i++) {
                if (fibSequence[i] === 0 || fibSequence[i - 1] === 0) continue;
                const proximity = parseFloat(calculateGoldenRatioProximity(fibSequence[i], fibSequence[i - 1]));
                if (proximity < closestPair.proximity) {
                    closestPair = { index: i, proximity: proximity };
                }
            }

            goldenRatioItem.innerHTML = `
                <h4>黄金比例分析</h4>
                <p>斐波那契数列中的连续数字比值会逐渐接近黄金比例 (1.618034)</p>
                <p>最接近黄金比例的是第 ${closestPair.index} 期和第 ${closestPair.index - 1} 期</p>
                <p>比值: <span class="golden-ratio">${fibSequence[closestPair.index] && fibSequence[closestPair.index - 1] ? (fibSequence[closestPair.index] / fibSequence[closestPair.index - 1]).toFixed(6) : "计算中..."}</span></p>
                <p>与黄金比例的差距: <span class="golden-ratio">${closestPair.proximity}</span></p>
            `;
            analysisContent.appendChild(goldenRatioItem);

            // 增长趋势分析
            const growthTrendItem = document.createElement('div');
            growthTrendItem.classList.add('analysis-item');

            // 计算平均增长率
            let totalGrowthRate = 0;
            let growthRateCount = 0;

            for (let i = 1; i < investmentAmounts.length; i++) {
                const rate = parseFloat(calculateGrowthRate(investmentAmounts[i], investmentAmounts[i - 1]));
                if (!isNaN(rate)) {
                    totalGrowthRate += rate;
                    growthRateCount++;
                }
            }

            const avgGrowthRate = growthRateCount > 0 ? (totalGrowthRate / growthRateCount).toFixed(2) : "0.00";

            growthTrendItem.innerHTML = `
                <h4>增长趋势分析</h4>
                <p>平均增长率: <span class="${parseFloat(avgGrowthRate) >= 0 ? 'growth-positive' : 'growth-negative'}">${avgGrowthRate}%</span></p>
                <p>根据斐波那契数列的特性，增长率会随着期数的增加而逐渐稳定。</p>
                <p>长期投资建议: 斐波那契数列展示了复利增长的力量，建议长期持有投资以获得最大收益。</p>
            `;
            analysisContent.appendChild(growthTrendItem);

            // 投资建议
            const recommendationItem = document.createElement('div');
            recommendationItem.classList.add('analysis-item');
            recommendationItem.innerHTML = `
                <h4>投资建议</h4>
                <p>1. 斐波那契回调水平 (23.6%, 38.2%, 61.8%) 是市场可能的支撑或阻力位。</p>
                <p>2. 考虑在斐波那契水平处设置买入或卖出点。</p>
                <p>3. 斐波那契数列的指数增长特性表明，长期投资策略通常优于短期交易。</p>
                <p>4. 市场价格经常在斐波那契水平处反弹，可以利用这一特性进行技术分析。</p>
            `;
            analysisContent.appendChild(recommendationItem);
        }
    </script>
</body>

</html>